import editForm from "../form.vue";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { type Ref, reactive, ref, onMounted, toRaw, h } from "vue";
import {
  getAgentOptionList,
  saveAgentOption,
  removeAgentOption
} from "@/api/agent";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import { agentOptionsType } from "@/utils/commonType";

export function useAgentOptions(tableRef: Ref) {
  const form = reactive({
    section: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 60
    },
    {
      label: "所属配置块",
      prop: "sectionName",
      minWidth: 100
    },
    {
      label: "配置项",
      prop: "optionItem",
      minWidth: 140
    },
    {
      label: "配置项说明",
      prop: "optionDesc"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  
  function handleSelectionChange(val) {
    // selectedNum.value = val.length;
    
    // tableRef.value.setAdaptive();
  }

  async function onSearch() {
    loading.value = true;
    const params={
      ...pagination,
      section:form.section
    }
    getAgentOptionList(params)
      .then(result => {
        dataList.value = result.data.list;
        pagination.total = result.data.total;
        pagination.pageSize = result.data.pageSize;
        pagination.currentPage = result.data.currentPage;
        pagination.pageCount = result.data.totalPage;
      })
      .catch(err => {
        message(`获取配置清单失败：${err.message}`, {
          type: "error"
        });
      });

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const formRef = ref();

  function handlleRemoveAgentOption(row) {
    const agentOptionItem = row.optionItem;
    removeAgentOption(row.pid)
      .then(result => {
        message(`成功删除代理配置项${agentOptionItem}`, {
          type: "success"
        });
        onSearch();
      })
      .catch(err => {
        message(`代理配置项${agentOptionItem}删除异常：${err.message}`, {
          type: "error"
        });
      });
  }

  function openDialog(title = "新增", row?: agentOptionsType) {
    addDialog({
      title: `${title}代理配置项`,
      props: {
        formInline: {
          pid: row?.pid ?? "",
          section: row?.section ?? "",
          optionItem: row?.optionItem ?? "",
          optionDesc: row?.optionDesc ?? "",
          editStatus: title == "新增" ? false : true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: false,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as agentOptionsType;
        function chores() {
          done(); // 关闭弹框
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            saveAgentOption(curData)
              .then(result => {
                message(`代理配置项保存成功`, {
                  type: "success"
                });
                chores();
                onSearch(); // 刷新表格数据
              })
              .catch(err => {
                message(`代理配置项保存异常：${err.message}`, {
                  type: "error"
                });
              });
          }
        });
      }
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    resetForm,
    openDialog,
    handlleRemoveAgentOption,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
